package org.kongqian.gift.service.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import org.kongqian.gift.config.Constant;
import org.kongqian.gift.domain.TenantType;
import org.kongqian.gift.mapper.TenantTypeMapper;
import org.kongqian.gift.service.ITenantTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kq
 * @since 2022-12-06
 */
@Service
public class TenantTypeServiceImpl extends ServiceImpl<TenantTypeMapper, TenantType> implements ITenantTypeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<TenantType> selectList(Wrapper<TenantType> wrapper) {
        //查询类型
        //从redis中查，返回
        Object o = redisTemplate.opsForValue().get(Constant.REDIS_CACHE_KEY);
        if (Objects.nonNull(o))
            return (List<TenantType>) o;

        //上锁
        RLock lock = redissonClient.getLock(Constant.REDIS_CACHE_KEY);
        List<TenantType> tenantTypes=null;
        try {
            lock.lock();
            //没有就从mysql中查，设置redis的值
            tenantTypes = super.selectList(wrapper);
            if (ObjectUtils.isEmpty(tenantTypes) || tenantTypes.size()<1){
                //进入这里说明数据库也没有，缓存也没有，防止穿透，设置空值
                tenantTypes=new ArrayList<>();
                return tenantTypes;
            }

            //设置redis的值
            redisTemplate.opsForValue().set(Constant.REDIS_CACHE_KEY, tenantTypes);
            return tenantTypes;

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return null;
    }

    //延时双删策略，第二次交给canal来监控数据库变化删除
    @Override
    public boolean insert(TenantType entity) {
        super.insert(entity);
        redisTemplate.delete(Constant.REDIS_CACHE_KEY);

        return true;
    }

    @Override
    public boolean deleteById(Serializable id) {
        super.deleteById(id);
        redisTemplate.delete(Constant.REDIS_CACHE_KEY);
        return true;
    }

    @Override
    public boolean updateById(TenantType entity) {
        super.updateById(entity);
        redisTemplate.delete(Constant.REDIS_CACHE_KEY);
        return true;
    }
}
